package com.gz.furnitures.web;

import com.gz.furnitures.entity.Furn;
import com.gz.furnitures.entity.Page;
import com.gz.furnitures.service.impl.FurnServiceImpl;
import com.gz.furnitures.utils.DataUtils;
import com.gz.furnitures.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@WebServlet(urlPatterns = "/manage/furnServlet")
public class FurnServlet extends BasicServlet {
    FurnServiceImpl furnService = new FurnServiceImpl();
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Furn> furns = furnService.queryFurns();
        //将集合放入request域
        request.setAttribute("furns", furns);
        request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request,response);
    }

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置分页
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.DEFAULT_PAGE_SIZE);
        Page<Furn> page = furnService.page(pageNo, pageSize);
        request.setAttribute("page", page);
        request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request,response);
    }

    protected  void showFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int idVal = DataUtils.parseInt(id, 0);
        Furn furn = furnService.queryFurnById(idVal);
        request.setAttribute("furn", furn);
        //注意，这里要区别request.setAttribute和request.getParameter两个域的值
        //(1)request.setAttribute -> requestScope(前端)或request.getAttribute(后端)获取
        //(2)前端提交的name对应的内容 -> param.xxx(前端)或request.getParameter(后端)获取
        request.setAttribute("pageNo", DataUtils.parseInt(request.getParameter("pageNo"), 1));
        request.getRequestDispatcher("/views/manage/furn_update.jsp").forward(request,response);
    }

    //考虑图片上传的版本
    protected void updateFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = DataUtils.parseInt(request.getParameter("id"),0);
        //获取对应的furn对象
        Furn furn = furnService.queryFurnById(id);
        if (furn == null) { //一般不恶意输入这种数据库没有的id的网址来访问，不会为空，可写可不写
            request.getRequestDispatcher("/index.jsp").forward(request,response);
            return;
        }

        //得到原来的图片路径(用于删除)
        String originalImgPath = furn.getImgPath();

        //1.判断是不是文件表单
        if(ServletFileUpload.isMultipartContent(request)){
            //2.创建DiskFileItemFactory对象，用于构建一个解析上传数据的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //<img id="prevView" class="img-responsive ml-3" src="${requestScope.furn.imgPath}"alt=""/>
            // <input type="file" name="imgPath" id="" value="${requestScope.furn.imgPath}" onchange="prev(this)"/>
            //3.创建一个解析上传数据的工具对象
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            //解决接收到的文件名是中文的乱码问题
            servletFileUpload.setHeaderEncoding("UTF-8");

            //4.关键地方，servletFileUpload 把表单提交给text文件
            //将其封装到FileItem文件中
            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);
                System.out.println("fileItems= " + fileItems);
                //fileItems= [name=4.png, StoreLocation=E:\Java\copy\apache-tomcat-9.0.99\temp\
                // upload_ad75d225_2746_4d93_9e1b_f85fc294eb48_00000000.tmp, size=158847 bytes,
                // isFormField=false, FieldName=pic, name=null, StoreLocation=null, size=0 bytes,
                // isFormField=true, FieldName=name]
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//如果是true就是文本 input text
                        if ("name".equals(fileItem.getFieldName())) {
                            furn.setName(fileItem.getString("UTF-8"));
                        } else if ("maker".equals(fileItem.getFieldName())) {
                            furn.setMaker(fileItem.getString("UTF-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            furn.setPrice(new BigDecimal(fileItem.getString("UTF-8")));
                        } else if ("sales".equals(fileItem.getFieldName())) {
                            furn.setSales(Integer.parseInt(fileItem.getString("UTF-8")));
                        } else if ("stock".equals(fileItem.getFieldName())) {
                            furn.setStock(Integer.parseInt(fileItem.getString("UTF-8")));
                        }
                    } else { //是一个文件
                        //获取上传文件的名字
                        String name = fileItem.getName();
                        System.out.println("上传的文件名= " + name);
                        if (!"".equals(name)) { //如果图片没修改，那么返回空，那么下面的不处理了
                            //将temp下的文件保存到你指定的目录
                            //1.指定一个目录
                            String filePath = "/" + WebUtils.FURN_IMG_DIRECTORY;
                            //获取完整目录
                            String realPath = request.getServletContext().getRealPath(filePath);
                            //创建这个上传的目录
                            //因为大部分文件不要保存到同一个文件，否则装不下
                            //所以做一个工具类来获得年月日，每次保存文件将文件名创建为路径+年月日(创建文件的日期)
                            String date=WebUtils.getYearMonthDay();
                            //这里是     目录
                            File fileRealPathDirectory = new File(realPath+"/"+date);
                            if (!fileRealPathDirectory.exists()) {
                                fileRealPathDirectory.mkdirs();
                            }

                            //4.将文件拷贝到fileRealPathDirectory
                            //为了防止文件名重复，可以添加前缀，保证唯一性,否则重复的话会覆盖
                            name = UUID.randomUUID() + "_" + System.currentTimeMillis() + "_" + name;

                            //这里是  目录+文件名
                            String fileFullPath = fileRealPathDirectory + "/" + name;
                            fileItem.write(new File(fileFullPath));

                            //查看新上传的图片在target里面看
                            //注意，上传时会创建文件夹和文件，这里可能看不到你创建的文件，但在target里面可以看到！！！

                            //关闭流
                            fileItem.getOutputStream().close();


                            //更新家居的图片路径
                            furn.setImgPath(WebUtils.FURN_IMG_DIRECTORY +"/"+date+ "/" + name);

                            //删除原来的图片
                            if (originalImgPath != null && !"".equals(originalImgPath)) {
                                String originalFullPath = request.getServletContext().getRealPath("/" + originalImgPath);
                                System.out.println(originalFullPath);
                                File originalFile = new File(originalFullPath);
                                if (originalFile.exists()) {
                                    originalFile.delete();
                                }
                            }
                        }
                    }
                }
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        furnService.updateFurn(furn);
        //请求转发到更新成功的页面
        response.sendRedirect(request.getContextPath()+"/manage/furnServlet?action=page&pageNo="+request.getParameter("pageNo"));
    }

//    protected void updateFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        Furn furn = DataUtils.copyParamToBean(request.getParameterMap(), new Furn());
////        System.out.println("furn= "+furn);
//        furnService.updateFurn(furn);
//        response.sendRedirect(request.getContextPath()+"/manage/furnServlet?action=page&pageNo="+request.getParameter("pageNo"));
//}


    protected void deleteFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        //数据库id不会有0,所有默认为0不会删除，安全
        furnService.deleteFurnById(DataUtils.parseInt(id, 0));

        //这里使用转发的话，当用户刷新页面时，会重新发出一次请求
        //造成重复删除
        //解决方案，使用重定向
        response.sendRedirect(request.getContextPath()+"/manage/furnServlet?action=page&pageNo="+DataUtils.parseInt(request.getParameter("pageNo"), 1));
    }

    protected void addFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //方式一
//        String name = request.getParameter("name");
//        String maker = request.getParameter("maker");
//        String price = request.getParameter("price");
//        String sales = request.getParameter("sales");
//        String stock = request.getParameter("stock");
//        Furn furn=null;
        //这里以后用springmvc可以有框架来处理，进行后端数据验证
//        try {
//            furn = new Furn(null,name,maker,new BigDecimal(price),
//                    new Integer(sales),new Integer(stock),"assets/images/product-image/default.jpg");
//        } catch (NumberFormatException e) {
//            System.out.println("数据格式错误");
//            request.setAttribute("msg", "数据格式错误");
//            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
//            return;
//        }
        //方式二(这里没有进行后端数据处理，默认后端数据是正确的)
//        Furn furn =new Furn();
//        try {
//            //使用反射将数据封装
//            //前提是表单提交的数据的字段名需要和封装的javaBean属性名一致
//            //这里imgPath为null,可以通过在Furn类中设置默认值来修改，然后在构造器中验证赋值
//            BeanUtils.populate(furn,request.getParameterMap());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //获取对应的furn对象
        Furn furn = new Furn();
        furn.setId(null);

        //1.判断是不是文件表单
        if(ServletFileUpload.isMultipartContent(request)){
            //2.创建DiskFileItemFactory对象，用于构建一个解析上传数据的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //<img id="prevView" class="img-responsive ml-3" src="${requestScope.furn.imgPath}"alt=""/>
            // <input type="file" name="imgPath" id="" value="${requestScope.furn.imgPath}" onchange="prev(this)"/>
            //3.创建一个解析上传数据的工具对象
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            //解决接收到的文件名是中文的乱码问题
            servletFileUpload.setHeaderEncoding("UTF-8");

            //4.关键地方，servletFileUpload 把表单提交给text文件
            //将其封装到FileItem文件中
            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);
                System.out.println("fileItems= " + fileItems);
                //fileItems= [name=4.png, StoreLocation=E:\Java\copy\apache-tomcat-9.0.99\temp\
                // upload_ad75d225_2746_4d93_9e1b_f85fc294eb48_00000000.tmp, size=158847 bytes,
                // isFormField=false, FieldName=pic, name=null, StoreLocation=null, size=0 bytes,
                // isFormField=true, FieldName=name]
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//如果是true就是文本 input text
                        if ("name".equals(fileItem.getFieldName())) {
                            furn.setName(fileItem.getString("UTF-8"));
                        } else if ("maker".equals(fileItem.getFieldName())) {
                            furn.setMaker(fileItem.getString("UTF-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            furn.setPrice(new BigDecimal(fileItem.getString("UTF-8")));
                        } else if ("sales".equals(fileItem.getFieldName())) {
                            furn.setSales(Integer.parseInt(fileItem.getString("UTF-8")));
                        } else if ("stock".equals(fileItem.getFieldName())) {
                            furn.setStock(Integer.parseInt(fileItem.getString("UTF-8")));
                        }
                    } else { //是一个文件
                        //获取上传文件的名字
                        String name = fileItem.getName();
                        System.out.println(" furn_add 上传的文件名= " + name);
                        //将temp下的文件保存到你指定的目录
                        //1.指定一个目录
                        String filePath = "/" + WebUtils.FURN_IMG_DIRECTORY;
                        //获取完整目录
                        String realPath = request.getServletContext().getRealPath(filePath);
                        //创建这个上传的目录
                        //因为大部分文件不要保存到同一个文件，否则装不下
                        //所以做一个工具类来获得年月日，每次保存文件将文件名创建为路径+年月日(创建文件的日期)
                        String date=WebUtils.getYearMonthDay();
                        //这里是     目录
                        File fileRealPathDirectory = new File(realPath+"/"+date);
                        if (!fileRealPathDirectory.exists()) {
                            fileRealPathDirectory.mkdirs();
                        }

                        //4.将文件拷贝到fileRealPathDirectory
                        //为了防止文件名重复，可以添加前缀，保证唯一性,否则重复的话会覆盖
                        name = UUID.randomUUID() + "_" + System.currentTimeMillis() + "_" + name;

                        //这里是  目录+文件名
                        String fileFullPath = fileRealPathDirectory + "/" + name;
                        fileItem.write(new File(fileFullPath));

                        //查看新上传的图片在target里面看
                        //注意，上传时会创建文件夹和文件，这里可能看不到你创建的文件，但在target里面可以看到！！！

                        //关闭流
                        fileItem.getOutputStream().close();

                        //更新家居的图片路径
                        furn.setImgPath(WebUtils.FURN_IMG_DIRECTORY +"/"+date+ "/" + name);

                        }
                    }
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        furnService.addFurn(furn);

//        request.getRequestDispatcher("/manage/furnServlet?action=list").forward(request,response);
        //这里使用转发的话，当用户刷新页面时，会重新发出一次请求
        //造成数据重复提交
        //解决方案，使用重定向
        response.sendRedirect(request.getContextPath()+"/manage/furnServlet?action=page&pageNo="+DataUtils.parseInt(request.getParameter("pageNo"), 1));
    }
}
